package models

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"time"
)

var TimeLocation = func() *time.Location {
	loc, _ := time.LoadLocation("Asia/Shanghai")
    return loc
}()

// JSONTime format json time field by myself
type JSONTime struct {
	time.Time
}

// MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S
func (ct JSONTime) MarshalJSON() ([]byte, error) {
	formatted := ct.Format("2006-01-02 15:04:05") // 统一格式化
	return json.Marshal(formatted)
}

func (ct *JSONTime) UnmarshalJSON(b []byte) (err error) {
	// 去掉 JSON 传入的双引号
	s := string(b)
	s = s[1 : len(s)-1]

	// 解析格式："YYYY-MM-DD HH:mm:ss"
	t, err := time.ParseInLocation("2006-01-02 15:04:05", s, TimeLocation)
	if err != nil {
		return err
	}

	ct.Time = t
	return nil
}

// Value insert timestamp into mysql need this function.
func (t JSONTime) Value() (driver.Value, error) {
	if t.IsZero() {
		return nil, nil
	}
	return t.Time, nil
}

// Scan valueof time.Time
func (t *JSONTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = JSONTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

// JSONTime format json time field by myself
type JSONTimeNoSeconds struct {
	time.Time
}

// MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S
func (ct JSONTimeNoSeconds) MarshalJSON() ([]byte, error) {
	formatted := ct.Format("2006-01-02 15:04") // 统一格式化
	return json.Marshal(formatted)
}

func (ct *JSONTimeNoSeconds) UnmarshalJSON(b []byte) (err error) {
	// 去掉 JSON 传入的双引号
	s := string(b)
	s = s[1 : len(s)-1]

	// 解析格式："YYYY-MM-DD HH:mm:ss"
	t, err := time.ParseInLocation("2006-01-02 15:04", s, TimeLocation)
	if err != nil {
		return err
	}

	ct.Time = t
	return nil
}

// Value insert timestamp into mysql need this function.
func (t JSONTimeNoSeconds) Value() (driver.Value, error) {
	if t.IsZero() {
		return nil, nil
	}
	return t.Time, nil
}

// Scan valueof time.Time
func (t *JSONTimeNoSeconds) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = JSONTimeNoSeconds{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}